﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Assets.Scripts.Tool;
using UnityEngine;

namespace Assets.Scripts.Net.Loader
{
    /// <summary>
    /// 资源加载管理器
    /// </summary>
    public class WWWLoadManager:Singleton<WWWLoadManager>
    {

        /// <summary>
        /// 加载的进度
        /// </summary>
        public float DownLoadProgress { get; set; }
        private float oldProgress { get; set; }


        /// <summary>
        /// 加载并且保存资源，实时写入配置文件
        /// </summary>
        /// <param name="urls"></param>
        /// <param name="finish"></param>
        /// <returns></returns>
        public IEnumerator DownLoadSaveResource(Dictionary<string, string>urls,Action finish)
        {
            DownLoadProgress = 0;
            StreamWriter sw = File.AppendText(NetConfig.NET_RES_CONFIG_PATH);
            foreach (KeyValuePair<string,string>pair in urls)
            {
                using (WWW www = new WWW(NetConfig.URL_RESHOST+pair.Value))
                {                    
                    while (!www.isDone)
                    {
                        oldProgress = www.progress;
                        yield return 1;
                        DownLoadProgress += (www.progress-oldProgress) / urls.Count;
                    }
                    yield return www;
                    if (www.isDone && www.error == null)
                    {
                        Debug.Log("下载图片的地址是：" + NetConfig.URL_RESHOST + pair.Value);
                        //加密资源
                        int index = pair.Value.LastIndexOf("/", StringComparison.Ordinal);
                        string fileName = pair.Value.Substring(index);
                        string resPath = NetConfig.NET_RES_PATH + fileName;
                        File.WriteAllBytes(resPath, EnCriptionTool.Encryption(www.bytes));//写入文件
                        //将加载的资源写入配置文件中
                        string line = pair.Key + "," + resPath;
                        sw.WriteLine(line);
                        Debug.Log("url:" + NetConfig.URL_RESHOST + pair.Value);
                    }
                    else
                    {
                        Debug.LogError(www.error+"        url:"+ NetConfig.URL_RESHOST + pair.Value);
                    }  
                }
            }
            sw.Close();
            sw.Dispose();
            urls.Clear();//每次加载完之后就清空需要加载资源urls，信息
            DownLoadProgress = 1;
            if (finish != null) finish();
        }

        /// <summary>
        /// 加载本地资源
        /// </summary>
        /// <returns></returns>
        public IEnumerator LoadLocalResource(string resPath,Action<byte[]> action)
        {
            if(string.IsNullOrEmpty(resPath))
                yield break;
            string path ="file:///"+ NetConfig.NET_RES_PATH + resPath.Substring(resPath.LastIndexOf("/", StringComparison.Ordinal));
            Debug.LogWarning("加载本地图片的地址是:"+path);
            using (WWW www=new WWW(path))
            {
                yield return www;
                if (www.isDone && www.error == null)
                {
                    if (action != null) action(EnCriptionTool.Decryption(www.bytes));
                }
                else
                {
                    Debug.Log(www.error);
                }
            }
        }
    }
}